<template>
  <div class="add-new-post">
    <div class="edit">
      <el-scrollbar height="600px">
        <div class="title">编辑发布</div>
        <div class="images">
          <div class="sub-title">编辑图片({{ postInfo.images.length }} /8)</div>
          <el-upload
            v-model:file-list="postInfo.images"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :disabled="postInfo.images.length >= 8 || postInfo.id"
            :on-change="uploadImages"
            :on-preview="handlePictureCardPreview"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </div>
        <div class="content">
          <div class="sub-title">正文内容</div>
          <el-form
            label-width="auto"
            style="width: 350px"
            ref="form"
            :model="postInfo"
            :rules="rules"
          >
            <!-- 标题 -->
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="postInfo.title"
                placeholder="在这里编辑记录的标题"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
            <!-- 正文内容 -->
            <el-form-item label="正文内容" prop="content">
              <el-input
                v-model="postInfo.content"
                class="content"
                autosize
                maxlength="800"
                show-word-limit
                type="content"
                clearable
                placeholder="在这里编辑记录的正文内容"
              />
            </el-form-item>
            <!-- 标签列 -->
            <el-form-item label="标签">
              <div class="tags">
                <el-tag
                  v-for="tag in postInfo.tags"
                  :key="tag"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="tagVisible"
                  ref="tagRef"
                  v-model="tag"
                  style="max-width: 100px"
                  class="w-20"
                  size="small"
                  maxlength="10"
                  show-word-limit
                  @keyup.enter="addNewTag"
                />
                <el-button
                  v-if="!tagVisible && postInfo.tags.length < 3"
                  class="button-new-tag"
                  size="small"
                  @click="tagVisible = true"
                >
                  + New Tag
                </el-button>
              </div>
            </el-form-item>
            <div class="range">
              <span>范围</span>
              <el-radio-group v-model="postInfo.isPrivate">
                <el-radio :value="1" size="large">仅自己可见</el-radio>
                <el-radio :value="0" size="large">公开</el-radio>
              </el-radio-group>
            </div>
          </el-form>
          <el-divider />
          <span class="description">
            <span style="font-size: 16px">用户须知：</span>
            <br />
            1.用户可以为商品上传至少一张且最多八张图片，并且默认第一张为封面，用户可以根据需要进行调整。
            <br />
            2.用户最多可以上传三个标签，标签更有利于其他用户查找商品。
            <br />
            3.用户可以选择是否公开，如果选择公开则所有人都可以看到该记录，如果选择仅自己可见则只有自己可以看到。
            <br />
            4.一旦发布记录，若编辑记录，则无法进行修改其中照片墙部分。
          </span>
          <div class="buttons" v-if="!postInfo.id">
            <el-button @click="addPost(1)">保存</el-button>
            <el-button type="primary" @click="addPost(0)">发布</el-button>
          </div>
          <div class="buttons" v-else>
            <el-button @click="$router.replace('/forum/post/addnewpost')">取消</el-button>
            <el-button type="primary" @click="updatePost">修改</el-button>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { getEditPost, savePost, updateEditPost } from '@/api/forum'
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { startLoading, stopLoading } from '@/utils/loading'

const router = useRouter()

const route = useRoute()

// 表单校验
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 20, message: '标题字数为1~20字之间', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入正文内容', trigger: 'blur' },
    { min: 1, max: 800, message: '标题字数为1~800字之间', trigger: 'blur' },
  ],
}

const form = ref()

// 标签添加
const tagVisible = ref(false)

// 标签
const tag = ref()

// 记录信息
const postInfo = ref({
  images: [],
  title: '',
  content: '',
  tags: [],
  isPrivate: 0,
  liked: 0,
  favoriteNum: 0,
})

const getEditPostInfo = async () => {
  const id = route.params.id
  if (id === '') {
    return
  }
  startLoading()
  const { data } = (await getEditPost(id)).data
  stopLoading()
  data.images = data.images.map((item) => {
    const newItem = { name: '图片', url: item }
    return newItem
  })
  postInfo.value = data
  postInfo.value.isPrivate = data.private ? 1 : 0
}

getEditPostInfo()

// 上传图片
const uploadImages = (file) => {
  if (postInfo.value.images.length >= 8) {
    ElNotification({
      title: '提示',
      message: '上传图片数量不能超过8张!',
      type: 'warning',
    })
    return false
  }
  // 判断格式
  const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
  if (!isJPG) {
    ElNotification({
      title: '提示',
      message: '上传图片只能是 JPG、PNG 格式!',
      type: 'warning',
    })
    return false
  }
  // 判断大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElNotification({
      title: '提示',
      message: '上传图片大小不能超过10MB',
      type: 'warning',
    })
    return false
  }
  // file.raw才是图片
  postInfo.value.images.push(file)
}

// 预览图片
const handlePictureCardPreview = (file) => {
  let url = null
  if (!postInfo.value.id) {
    url = URL.createObjectURL(file.raw)
  }
  url = file.url
  ElMessageBox.alert(
    `<img src="${url}" style="max-width: 100%; height: auto; display: block; margin: 0 auto" />`,
    '预览',
    {
      dangerouslyUseHTMLString: true,
      draggable: true,
      confirmButtonText: '关闭',
    },
  )
}

// 新增标签
const addNewTag = () => {
  if (tag.value) {
    postInfo.value.tags.push(tag.value)
    tagVisible.value = false
    tag.value = ''
  }
}

// 删除标签
const handleClose = (tag) => {
  postInfo.value.tags.splice(postInfo.value.tags.indexOf(tag), 1)
}

// 发布记录
const addPost = async (type) => {
  await form.value.validate()

  const formData = new FormData()

  for (let key in postInfo.value) {
    if (key !== 'images') {
      formData.append(key, postInfo.value[key])
    }
  }
  // 将图片信息添加到 formData 中
  postInfo.value.images.forEach((item, index) => {
    formData.append(`images`, item.raw)
  })
  formData.append('isSave', type)

  startLoading()
  const res = (await savePost(formData)).data
  stopLoading()
  if (res.success) {
    ElNotification({
      title: '成功',
      message: '发布成功',
      type: 'success',
    })
    router.push('/forum')
  } else {
    ElNotification({
      title: '失败',
      message: '发布失败，请稍后重试',
      type: 'error',
    })
  }
}

// 更新记录
const updatePost = async () => {
  postInfo.value.images = postInfo.value.images.map((item) => {
    const newItem = item.url
    return newItem
  })
  startLoading()
  const res = (
    await updateEditPost({ ...postInfo.value, privateCondition: postInfo.value.isPrivate })
  ).data
  stopLoading()
  if (res.success) {
    ElNotification({
      title: '成功',
      message: '更新成功',
      type: 'success',
    })
    router.replace('/forum/post/managepost')
  } else {
    ElNotification({
      title: '失败',
      message: '更新失败，请稍后重试',
      type: 'error',
    })
  }
}
</script>

<style scoped less="scss">
.add-new-post {
  height: 600px;

  .edit {
    width: 100%;

    .title {
      font-size: 20px;
      margin: 10px 20px;
    }

    .sub-title {
      font-size: 18px;
      color: grey;
      margin: 15px 0 10px 0;
    }

    .images {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: start;

      height: 200px;
      margin-left: 15px;
    }

    .content {
      margin-left: 15px;

      .content {
        min-width: 800px;
      }

      .tags {
        display: flex;
        gap: 3px;
      }

      .range {
        display: flex;
        justify-content: start;
        align-items: center;
        gap: 15px;

        color: #606266;
        font-size: 14px;
        margin-left: 28px;
      }

      .description {
        font-size: 14px;
        color: grey;
      }

      .buttons {
        display: flex;
        justify-content: end;
        margin: 0 20px 10px 0;
      }
    }
  }
}
</style>
